from django.db import models
from utils.models import BaseModel
from django.core.cache import cache
import logging
logging = logging.getLogger('django')
# Create your models here.



# 这是你自己的模型，展示页面用的
class NavCategory(BaseModel):

    name = models.CharField(max_length=100,verbose_name='名称')
    display_name = models.CharField(max_length=100,verbose_name='显示名称')
    weight = models.IntegerField(default=0,verbose_name='权重')
    link = models.URLField(blank=True,verbose_name='外链地址')

    class Meta:
        db_table = 'tb_nav_category'
        ordering = ['-weight']
        # 排序的话 记得要倒序，或者你把数据搞升序，不然显示就不再前面了

    def __str__(self):
        return self.name





class CourseCategory(BaseModel):

    name = models.CharField(max_length=100,verbose_name='侧边名称')
    level = models.IntegerField(verbose_name='侧边级别')
    description = models.CharField(max_length=100,verbose_name='描述')
    parent = models.ForeignKey('self',on_delete=models.CASCADE,blank=True,null=True,verbose_name='父级分类')
    # pid 自关联

    class Meta:
        db_table = 'tb_course_category'

    def __str__(self):
        return self.name


    def save(self,*args,**kwargs):

        super().save(*args,**kwargs)
        # 清除缓存
        cache_key = 'code_mirror:home:behind'
        cache.delete(cache_key)  # 直接删除


    def delete(self,*args,**kwargs):
        super().delete(*args,**kwargs)
        cache_key = 'code_mirror:home:behind'
        cache.delete(cache_key)  # 直接删除






class Image(BaseModel):

    title = models.CharField(max_length=100)
    image = models.CharField(max_length=100)
    link = models.URLField(max_length=100)
    description = models.CharField(max_length=100)

    class Meta:
        db_table = 'image'



    def save(self, *args, **kwargs):
        # 重写save修改提交方法，在保存数据时，自动清除缓存
        super().save(*args, **kwargs)
        # 清除缓存
        # 定义redis数据的键-->键取值
        cache_key = 'code_mirror:home:image'
        # delete方法清除redis中的数据
        cache.delete(cache_key)  # 直接删除


    def delete(self, *args, **kwargs):
        # 重写delete方法, 在mysql删除数据时, redis自动清除缓存
        super().delete(*args, **kwargs)
        # 定义redis数据的键-->键取值
        cache_key = 'code_mirror:home:image'
        # delete方法清除redis中的数据
        logging.info(f'删除了图片数据，清除缓存')
        cache.delete(cache_key)  # 直接删除




